<?php
/**
 * Created by PhpStorm.
 * User: 技术员专用
 * Date: 2019/3/19
 * Time: 14:30
 */
class Http{
    const HOST='0.0.0.0';
    const PORT=8811;

    public $http=null;
    public function __construct()
    {
        $this->http=new swoole_http_server(self::HOST,self::PORT);
        $this->http->set([
            'document_root' => '/www/wwwroot/live/tp5/public/static',
            'enable_static_handler' => true,
            'worker_num'=>2,
            'task_worker_num'=>2,
        ]);
        $this->http->on('WorkerStart',[$this,'onWorkerStart']);
        $this->http->on('request',[$this,'onRequest']);
        $this->http->on('task',[$this,'onTask']);
        $this->http->on('finish',[$this,'onFinish']);
        $this->http->start();
    }

    /**
     * WorkerStart回调
     * @param swoole_server $server
     * @param $worker_id
     */
    public function onWorkerStart($server, $worker_id){
        define('APP_PATH', __DIR__ . '/../application/');
        require __DIR__ . '/../thinkphp/base.php';
    }

    /**
     * request回调
     * @param $request
     * @param $response
     */
    public function onRequest($request, $response){
        $_SERVER=[];
        $_GET=[];
        $_POST=[];
        if (isset($request->server)) {
            foreach ($request->server as $k => $v) {
                $_SERVER[strtoupper($k)] = $v;
            }
        }
        if (isset($request->header)) {
            foreach ($request->header as $k => $v) {
                $_SERVER[strtoupper($k)] = $v;
            }
        }
        if (isset($request->get)) {
            foreach ($request->get as $k => $v) {
                $_GET[$k] = $v;
            }
        }
        if (isset($request->post)) {
            foreach ($request->post as $k => $v) {
                $_POST[$k] = $v;
            }
        }
        $_SERVER['http_server']=$this->http;
        ob_start();
        // 执行应用并响应
        try{
            think\Container::get('app',[APP_PATH])->run()->send();
        }catch (Exception $e){
            //todo
        }
        $res = ob_get_contents();
        if(ob_get_contents()) ob_end_clean();
        $response->end($res);
    }
    public function onTask($serv,$taskId,$workId,$data){
        //分发Task任务机制，不同任务执行不同逻辑
        $obj=new app\common\lib\task\Task();
        $method=$data['method'];
        $flag=$obj->$method($data['data']);
        return $flag;
    }
    public function onFinish($serv,$taskId,$data){
        echo "task-id:$taskId".PHP_EOL;
        echo "finish-data-success:$data".PHP_EOL;
    }
}
new Http();